package com.shaonianyou.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

@Controller
public class WechatMenuController {

	@Autowired
	RestTemplate restTemplate;

	@Value("${rest.restClient.servicePrefix}")
	String prefix;

	@Value("${wechat.app.appId}")
	String appId;

	@Value("${wechat.app.appSecret}")
	String appSecret;

	/**
	 * 微信菜单入口
	 * 
	 * @param state
	 * @param model
	 * @param request
	 * @param hiddenMenuId
	 *            默认跳转菜单
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/wechat/{hiddenMenuId}", method = RequestMethod.GET)
	public String wechatMenu(String state, Model model, HttpServletRequest request, @PathVariable String hiddenMenuId) {
		String code = request.getParameter("code");
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + appSecret
				+ "&code=" + code + "&grant_type=authorization_code";
		JSONObject result = restTemplate.getForObject(url, JSONObject.class, Maps.newHashMap());
		String openid = String.valueOf(result.get("openid"));
		String access_token = String.valueOf(result.get("access_token"));
		Map<String, Object> param = Maps.newHashMap();
		param.put("openid", openid);
		param.put("accessToken", access_token);
		Map<String, Object> resultMap = restTemplate.postForObject(prefix + "/findCustByOpenid", param, Map.class);
		Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
//		Map<String, Object> dataMap = Maps.newHashMap();
//		dataMap.put("custId", "13");
		if (dataMap != null && dataMap.containsKey("custId")) {
			request.getSession().setAttribute("custId", dataMap.get("custId"));
			model.addAttribute("status", dataMap.get("status"));
			model.addAttribute("hiddenMenuId", hiddenMenuId);
			return "index";
		} else {
			model.addAttribute("openid", openid);
			return "login";
		}

	}

}
